<?php
namespace app\faxing\channel;

use app\common\model\Gameulog;
use app\common\model\Order;
use app\common\model\Player;
use app\common\model\PlayerRole;
use app\index\controller\Exception;
use think\cache\driver\Redis;
use think\Db;
use think\facade\Log;
use think\facade\Session;
use app\common\controller\FaXingBase;

/**
 * 后台首页
 * Class Index
 * @package app\admin\controller
 */
class Yy extends FaXingBase
{
    public function register($params)
    {
        $cid = $params['cid'];
        $account = $cid."_".$params['uid'];
        $player = Player::getOne(['account'=>$account]);
        if(!$player){
            //注册
            $data['account'] = $account;
            $data['password'] = get_encrypt('123456');
            $data['type'] = 0;
            $data['cid'] = $cid;
            $data['gid'] = $this->gid;
            // 获取防沉迷信息
            try {
                Db::startTrans();
                $player = Player::register($data);
                Db::commit();
            }catch (Exception $e) {
                Db::rollback();
                $this->error("登录失败，请稍后再试。");
                Log::info("用户注册失败:".$e->getMessage());
            }
        }
        $game = $this->game;
        $data['uid'] = $player['id'];
        //记录登录信息
        Gameulog::addLog($data);
        $token = get_encrypt($data['uid']);
        $player['token'] = $token;
        unset($player['password']);
        Session::set('palyerinfo', json_encode($player));
        //redis 保存用户信息
        $redis = new Redis();
        $redis->set($token, $player);
        if (strpos($game['api_login_url'], '?') !== false) {
            $game_url = $game['api_login_url']."&token=".$token;
        } else {
            $game_url = $game['api_login_url']."?token=".$token;
        }
        return ['game_url'=>$game_url,'token'=>$token];
    }
    public function order($order)
    {
        $game_name = get_game_filed($order['gid'],'name');
        $role = PlayerRole::where(['gid'=>$order['gid'],'uid'=>$order['uid'],'cid'=>$order['cid']])->find();

        $agent = getGameAgent($order['cid'],$order['gid'],'extdata');
        $data = [
            'sdkOrderId'=>$order['order_no'],//订单号
            'amount'=>$order['amount'],//金额 整数：元
            'prodId'=>rand(000000,999999),//商品id
            'prodName'=>$order['goods_name'],//商品名称
            'prodDesc'=>$order['goods_name'],//商品描述
            'gameName'=>$game_name,//游戏名称
            'roleId'=>$role['role_id'] ?? 0,//角色id
            'roleName'=>$role['role_name'] ?? "",//角色名称
            'serverId'=>$role['sid'] ?? '0',//区服id
            'serverName'=>$role['sid'] ?? '0',//区服名称
            'extData'=> get_sign(['order_no'=>$order['order_no']],$agent['Appkey']) // 回传验证
        ];
        return $data;
    }

    public function check_order($params)
    {
        // 查询订单
        $order = Order::where([
            'order_no'=>$params['sdkOrderId']
        ])->find();
        $agent = getGameAgent($order['cid'],$order['gid'],'extdata');

        if(!$this->check_sign($params,$agent['Appkey'])){
            echo json_encode(['status'=>-11,'message'=>'签名错误']);exit;
        }
        // 双重校验
        $order_sign = get_sign(['order_no'=>$params['sdkOrderId']],$agent['Appkey']);

        if($order_sign != $params['extData']){
            echo json_encode(['status'=>-11,'message'=>'签名错误']);exit;
        }

        if($order['amount'] != $params['amount']){
            echo json_encode(['status'=>-11,'message'=>'金额错误']);exit;
        }

        return $order;
    }

    public function message($message)
    {
        echo $message === 'success' ? json_encode(['status'=>200,'message'=>'成功']) :  json_encode(['status'=>-11,'message'=>'订单不存在']);
        exit;
    }

    protected function check_sign($params, $key)
    {

        $sign = $params['sign'];
        unset($params['sign']);
        $check_sign = get_sign($params,$key);
        if($check_sign != $sign){
            return false;
        }
        return true;
    }
}